package com.jinghua.treatment.wechat.biz;

import com.alibaba.fastjson.JSONObject;
import com.jinghua.treatment.entity.SysDoctor;
import com.jinghua.treatment.entity.SysWechatAccount;
import com.jinghua.treatment.mapper.SysDoctorMapper;
import com.jinghua.treatment.mapper.SysWechatAccountMapper;
import com.jinghua.treatment.tools.IDGenerator;
import com.jinghua.treatment.tools.PropertyUtil;
import com.jinghua.treatment.wechat.entity.TextXML;
import com.jinghua.treatment.wechat.util.HttpUtil;
import com.jinghua.treatment.wechat.util.WechatUtil;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.List;

@Component
public class WechatBiz {


    @Autowired
    private SysDoctorMapper sysDoctorMapper;

    @Autowired
    private SysWechatAccountMapper sysWechatAccountMapper;

    Logger log = LogManager.getLogger(WechatBiz.class);


    @Transactional
    public void doBussiness(Document document, HttpServletRequest request, HttpServletResponse response) throws IOException {
        Element root = document.getRootElement();
        String msgType = root.selectSingleNode("MsgType").getText();
        if ("text".equals(msgType)) {
            TextXML textXML = parseTextObject(root);
            if ("ys".equals(textXML.getContent())) {
                String doctorWechatId = textXML.getFromUserName();
                SysWechatAccount example = new SysWechatAccount();
                example.setOpenid(doctorWechatId);
                List<SysWechatAccount> wechatAccounts = sysWechatAccountMapper.selectByExample(example);
                if (wechatAccounts != null && wechatAccounts.size() > 0) {//已经绑定微信
                    SysWechatAccount sysWechatAccount = wechatAccounts.get(0);
                    //查看是否认证,先查看有没有此医生
                    SysDoctor docExample = new SysDoctor();
                    docExample.setWechat(doctorWechatId);
                    List<SysDoctor> sysDoctors = sysDoctorMapper.selectByExample(docExample);
                    if (sysDoctors != null && sysDoctors.size() > 0) {//有，再查看有没有认证
                        SysDoctor sysDoctor = sysDoctors.get(0);
                        if (sysDoctor.getIsauthentication() == 1) {//已认证，引导到医生主界面

                        } else {//未认证，引导到医生认证界面

                        }
                    } else {//没有注册，引导到医生注册页面
                        String xml = buildTWXML(doctorWechatId, sysWechatAccount.getNickname() + ",欢迎您，您还未注册为医师，请先注册",
                                "http://kriss1984.gnway.cc/static/images/doctor_reg_guide.jpg",
                                "http://kriss1984.gnway.cc/index.html#/sufferer?doctorId=3",
                                "前往注册医师-->");
                        response.getWriter().write(xml);
                    }
                } else {//未绑定微信
                    String accessToken = WechatUtil.getAccessToken();
                    String url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + accessToken + "&openid=" + textXML.getFromUserName() + "&lang=zh_CN";
                    String responseJson = HttpUtil.sendGetRequest(url, null);
                    log.debug("responseJson:" + responseJson);
                    SysWechatAccount sysWechatAccount = JSONObject.parseObject(responseJson, SysWechatAccount.class);
                    sysWechatAccount.setUuid(IDGenerator.uuid());
                    System.out.println(sysWechatAccount.getHeadimgurl());
                    //WechatUtil.parseJsonToObject(responseXml, sysWechatAccount);

                    //获取医生二维码路径，用于医生识别
                    String qrUrl = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" + accessToken;
                    String params = "{\"action_name\": \"QR_LIMIT_STR_SCENE\", \"action_info\": {\"scene\": {\"scene_str\": \""+sysWechatAccount.getOpenid()+"\"}}}";
                    String qrUrlResponseJson = HttpUtil.sendPostRequest(qrUrl, params);
                    sysWechatAccountMapper.insert(sysWechatAccount);
                    //插入完毕后引导到注册页面
                    String xml = buildTWXML(doctorWechatId, sysWechatAccount.getNickname() + ",欢迎您，您还未注册为医师，请先注册",
                            "http://kriss1984.gnway.cc/static/images/doctor_reg_guide.jpg",
                            "http://kriss1984.gnway.cc/index.html#/sufferer?doctorId=3",
                            "请完成注册信息");
                    response.getWriter().write(xml);
                }
            }
        }else if("event".equals(msgType)){//微信推送的事件，如用户关注等
            //获取Event 字段
            String eventType = root.selectSingleNode("Event").getText();//这里event 有7中，目前只处理扫描了医生扫描了二维码后的场景
            System.out.println("xml:" + root.asXML());
            if("subscribe".equals(eventType)){//用户之前没有关注过公众号的 推送

            }else if("SCAN".equals(eventType)){//用户已经关注过公众号

            }
        }
    }


    /**
     * 构建图文消息
     *
     * @return
     */
    private String buildTWXML(String toUser, String title, String img, String link, String desc) {
        return "<xml><ToUserName><![CDATA[" + toUser + "]]></ToUserName><FromUserName><![CDATA[" + PropertyUtil.getConfig("wechat.originId") + "]]></FromUserName>" +
                "<CreateTime>" + new Date().getTime() + "</CreateTime><MsgType><![CDATA[news]]></MsgType><ArticleCount>1</ArticleCount><Articles><item>" +
                "<Title><![CDATA[" + title + "]]></Title> <Description><![CDATA[" + desc + "]]></Description><PicUrl><![CDATA[" + img + "]]>" +
                "</PicUrl><Url><![CDATA[" + link + "]]></Url></item></Articles></xml>";
    }


    private TextXML parseTextObject(Element root) {
        // toUserName,  fromUserName,  createTime,  msgType,  content,  msgId
        return new TextXML(root.selectSingleNode("ToUserName").getText(),
                root.selectSingleNode("FromUserName").getText(),
                root.selectSingleNode("CreateTime").getText(),
                root.selectSingleNode("MsgType").getText(),
                root.selectSingleNode("Content").getText(),
                root.selectSingleNode("MsgId").getText());
    }
}
